package com.xmall.service.impl;

import com.github.pagehelper.PageInfo;
import com.xmall.bean.table.Ad;
import com.xmall.bean.table.AdExample;
import com.xmall.mapper.AdMapper;
import com.xmall.service.AdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdServiceImpl implements AdService {

    @Autowired
    private AdMapper adMapper;

    @Override
    public Map<String, Object> queryList(Map<String, String> params) {
        //分页
        PageHelper.startPage(Integer.parseInt(params.get("page")),Integer.parseInt(params.get("limit")));

        AdExample adExample = new AdExample();
        adExample.setOrderByClause(params.get("sort") + " " +params.get("order"));
        AdExample.Criteria criteria = adExample.createCriteria();

        if (params.get("name") != null){
            criteria.andNameLike("%" + params.get("name") + "%");
        }
        if (params.get("content") != null){
            criteria.andContentLike("%" +params.get("content")+ "%");
        }
        //逻辑删除，所有筛选出deleted 为false 的
        criteria.andDeletedEqualTo(false);
        List<Ad> ads = adMapper.selectByExample(adExample);
        HashMap<String, Object> result = new HashMap<>();
        result.put("items",ads);
        PageInfo<Ad> adPageInfo = new PageInfo<>(ads);
        long total = adPageInfo.getTotal();
        result.put("total",total);
        return result;
    }
//todo admin/create
    @Override
    public Ad createAd(Ad ad) {
        ad.setAddTime(new Date());
        ad.setUpdateTime(new Date());
        adMapper.insertSelective(ad);
        return ad;
    }

    @Override
    public Ad updateAd(Ad adUpdate) {
        adUpdate.setUpdateTime(new Date());
        adMapper.updateByPrimaryKeySelective(adUpdate);
        return adUpdate;
    }

    @Override
    public void deleteAd(Ad adDelete) {
        //逻辑删除
        adDelete.setDeleted(true);
        updateAd(adDelete);
    }
}
